{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "40885b4b",
   "metadata": {},
   "source": [
    "# Rainbow options with bruteforce methodology\n",
    "\n",
    "In this Notebook we will go through the implementation using QMOD for the rainbow option.\n",
    "This Notebook role is to verify result of different metodology on a smal scale problem, as it grows exponentially in the gate count."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e7f7681",
   "metadata": {},
   "source": [
    "### Introduction\n",
    "\n",
    "In finance, a crucial aspect of asset pricing pertains to derivatives.\n",
    "Derivatives are contracts whose value is contingent upon another source, known as the underlying.\n",
    "The pricing of options, a specific derivative instrument, involves determining the fair market value (discounted payoff) of contracts affording their holders the right, though not the obligation, to buy (call) or sell (put) one or more underlying assets at a predefined strike price by a specified future expiration date (maturity date).\n",
    "This process relies on mathematical models, considering variables like current asset prices, time to expiration, volatility, and interest rates."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbfd7ac4",
   "metadata": {},
   "source": [
    "## Data Definitions\n",
    "\n",
    "The problem inputs are:\n",
    "- `NUM_QUBITS`: the number of qubits representing an underlying asset\n",
    "- `NUM_ASSETS`: the number of underlying assets\n",
    "- `K`: the strike price\n",
    "- `S0`: the arrays of underlying assets prices\n",
    "- `dt`: the number of days to the maturity date\n",
    "- `COV`: the covariance matrix that correlate the underlyings\n",
    "- `MU_LOG_RET`: the array containing the mean of the log return of each underlyings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "57ba289d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import scipy\n",
    "\n",
    "NUM_QUBITS = 2\n",
    "NUM_ASSETS = 2\n",
    "\n",
    "K = 190\n",
    "S0 = [193.97, 189.12]\n",
    "dt = 250\n",
    "\n",
    "COV = np.array([[0.000335, 0.000257], [0.000257, 0.000418]])\n",
    "MU_LOG_RET = np.array([0.00050963, 0.00062552])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "09b0b7cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "MU = MU_LOG_RET * dt\n",
    "CHOLESKY = np.linalg.cholesky(COV) * np.sqrt(dt)\n",
    "SCALING_FACTOR = 1 / CHOLESKY[0, 0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d55b62c",
   "metadata": {},
   "source": [
    "## Gaussian State preparation\n",
    "Encode the probability distribution of a discrete multivariate random variable $W$ taking values in $\\{w_0, .., w_{N-1}\\}$ describing the assets' prices at the maturity date. The number of discretized values, denoted as $N$, depends on the precision of the state preparation module and is consequently connected to the number of qubits ($n=$) according to the formula $N=2^n$. \n",
    "\n",
    "$$\n",
    "\\sum_{i=0}^{N-1} \\sqrt{p(w_i)}\\left|w_i\\right\\rangle \n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b340d198",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:40:28.838996Z",
     "start_time": "2024-04-01T09:40:28.226590Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "def gaussian_discretization(num_qubits, mu=0, sigma=1, stds_around_mean_to_include=3):\n",
    "    lower = mu - stds_around_mean_to_include * sigma\n",
    "    upper = mu + stds_around_mean_to_include * sigma\n",
    "    num_of_bins = 2**num_qubits\n",
    "    sample_points = np.linspace(lower, upper, num_of_bins + 1)\n",
    "\n",
    "    def single_gaussian(x: np.ndarray, _mu: float, _sigma: float) -> np.ndarray:\n",
    "        cdf = scipy.stats.norm.cdf(x, loc=_mu, scale=_sigma)\n",
    "        return cdf[1:] - cdf[0:-1]\n",
    "\n",
    "    non_normalized_pmf = (single_gaussian(sample_points, mu, sigma),)\n",
    "    real_probs = non_normalized_pmf / np.sum(non_normalized_pmf)\n",
    "    return sample_points[:-1], real_probs[0].tolist()\n",
    "\n",
    "\n",
    "grid_points, probabilities = gaussian_discretization(NUM_QUBITS)\n",
    "\n",
    "STEP_X = grid_points[1] - grid_points[0]\n",
    "MIN_X = grid_points[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20ae5a04",
   "metadata": {},
   "source": [
    "### SANITY CHECK"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebae55f2",
   "metadata": {},
   "source": [
    "The process must be stopped if the strike price $K$ is greater than the maximum value reacheable by the assets during the simulation, to avoid meaningless results. The payoff is $0$ in this case, so there is no need to simulate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "689ede4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import Markdown\n",
    "\n",
    "if K >= max(S0*np.exp(np.dot(CHOLESKY,[grid_points[-1]]*2) + MU)):\n",
    "    display(Markdown('<font color=\\'red\\'> K always greater than the maximum asset values. Stop the run, the payoff is 0</font>'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d409419",
   "metadata": {},
   "source": [
    "## Maximum Computation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8436bda6",
   "metadata": {},
   "source": [
    "### Precision utils"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "cf0bdcc6",
   "metadata": {},
   "outputs": [],
   "source": [
    "FRAC_PLACES = 1\n",
    "\n",
    "def round_factor(a):\n",
    "    precision_factor = 2 ** (FRAC_PLACES)\n",
    "    return np.floor(a * precision_factor) / precision_factor\n",
    "\n",
    "def floor_factor(a):\n",
    "    precision_factor = 2 ** (FRAC_PLACES)\n",
    "    return np.floor(a * precision_factor) / precision_factor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3286714b",
   "metadata": {},
   "source": [
    "### Affine and maximum arithmetic definitions\n",
    "\n",
    "Considering the time delta between the starting date ($t_0$) and the maturity date ($t$), we can express the return value $R_i$ for the $i$-th asset as $R_i = \\mu_i + y_i$. Where:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ec80251",
   "metadata": {},
   "source": [
    "  $\\mu_i= (t-t_0)\\tilde{\\mu}_i$, being $\\tilde{\\mu}_i$ the expected daily log-return value. It can be estimated by considering the historical time series of log returns for the $i$-th asset."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b00dbbf4",
   "metadata": {},
   "source": [
    "$y_i$ is obtained through the dot product between the matrix $\\mathbf{L}$ and the standard multivariate Gaussian sample:\n",
    "\n",
    "$$    y_i = \\Delta x \\cdot \\sum_kl_{ik}d_k + x_{min} \\cdot \\sum_k l_{ik} $$\n",
    "$\\Delta x$ is the Gaussian discretization step, $x_{min}$ is the lower Gaussian truncation value and $d_k \\in [0,2^m-1]$ is the sample taken from the $k$-th standard Gaussian.\n",
    "$l_{ik}$ is the $i,k$ entry of the matrix $\\mathbf{L}$, defined as $\\mathbf{L}=\\mathbf{C}\\sqrt{(t-t_0)}$, where $\\mathbf{C}$ is the lower triangular matrix obtained by applying the Cholesky decomposition to the historical daily log-returns correlation matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ac8e3341",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:40:28.981781Z",
     "start_time": "2024-04-01T09:40:28.258352Z"
    }
   },
   "outputs": [],
   "source": [
    "from functools import reduce\n",
    "\n",
    "from classiq import QNum, get_expression_numeric_attributes, qfunc, Output\n",
    "from classiq.qmod.symbolic import max as qmax\n",
    "\n",
    "a = STEP_X / SCALING_FACTOR\n",
    "b = np.log(S0[0]) + MU[0] + MIN_X * CHOLESKY[0].sum()\n",
    "\n",
    "\n",
    "def get_affine_formula(assets, i):\n",
    "    return reduce(\n",
    "        lambda x, y: x + y,\n",
    "        [\n",
    "            assets[j] * round_factor(SCALING_FACTOR * CHOLESKY[i, j])\n",
    "            for j in range(NUM_ASSETS)\n",
    "            if CHOLESKY[i, j]\n",
    "        ],\n",
    "    )\n",
    "\n",
    "\n",
    "c = (\n",
    "    SCALING_FACTOR\n",
    "    * (\n",
    "        np.log(S0[1])\n",
    "        + MU[1]\n",
    "        - (np.log(S0[0]) + MU[0])\n",
    "        + MIN_X * sum(CHOLESKY[1] - CHOLESKY[0])\n",
    "    )\n",
    "    / (STEP_X)\n",
    ")\n",
    "\n",
    "c = round_factor(c)\n",
    "\n",
    "\n",
    "def calculate_max_reg_type():\n",
    "    x1 = QNum(\"x1\", NUM_QUBITS, False, 0)\n",
    "    x2 = QNum(\"x2\", NUM_QUBITS, False, 0)\n",
    "    expr = qmax(get_affine_formula([x1, x2], 0), get_affine_formula([x1, x2], 1) + c)\n",
    "    size_in_bits, sign, fraction_digits = get_expression_numeric_attributes(\n",
    "        [x1, x2], expr\n",
    "    )\n",
    "    return size_in_bits, fraction_digits\n",
    "\n",
    "\n",
    "MAX_NUM_QUBITS = calculate_max_reg_type()[0]\n",
    "MAX_FRAC_PLACES = calculate_max_reg_type()[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d317e6f8",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:40:33.708342Z",
     "start_time": "2024-04-01T09:40:28.276656Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "@qfunc\n",
    "def affine_max(x1: QNum, x2: QNum, res: Output[QNum]):\n",
    "    res |= qmax(get_affine_formula([x1, x2], 0), get_affine_formula([x1, x2], 1) + c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b5f983a",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Brute-Force Amplitude Loading Method"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71345ed8",
   "metadata": {},
   "source": [
    "This type of amplitude loading has an exponential scale, is therefore used as a \"sanity check\" method for validating result from the direct method and integration method that are part of the paper [[1]](#QALROP)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "2b72d3d2",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:41:09.372257Z",
     "start_time": "2024-04-01T09:41:06.237959Z"
    }
   },
   "outputs": [],
   "source": [
    "from classiq import QBit, Constraints, synthesize, create_model, allocate, inplace_prepare_state, within_apply, control, bind, show\n",
    "from classiq.qmod.symbolic import sqrt, exp\n",
    "\n",
    "def get_payoff_expression(x, size, fraction_digits):\n",
    "    payoff = sqrt(\n",
    "        qmax(\n",
    "            S0[0]\n",
    "            * exp(\n",
    "                STEP_X / SCALING_FACTOR * (2 ** (size - fraction_digits)) * x\n",
    "                + (MU[0] + MIN_X * CHOLESKY[0].sum())\n",
    "            ),\n",
    "            K,\n",
    "        )\n",
    "    )\n",
    "    return payoff\n",
    "\n",
    "def get_payoff_expression_normalized(x: QNum, size, fraction_digits):\n",
    "    x_max = 1 - 1 / (2**size)\n",
    "    payoff_max = get_payoff_expression(x_max, size, fraction_digits)\n",
    "    payoff = get_payoff_expression(x, size, fraction_digits)\n",
    "    return payoff / payoff_max\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def brute_force_payoff(max_reg: QNum, ind_reg: QBit):\n",
    "    max_reg_fixed = QNum(\"max_reg_fixed\", max_reg.size, False, max_reg.size)\n",
    "    bind(max_reg, max_reg_fixed)\n",
    "    ind_reg *= get_payoff_expression_normalized(\n",
    "        max_reg_fixed, max_reg.size, max_reg.fraction_digits\n",
    "    )\n",
    "    bind(max_reg_fixed, max_reg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c446dca7",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:41:17.213486Z",
     "start_time": "2024-04-01T09:41:09.412227Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/1ac13cf9-2885-4d95-8b82-9ca4f809f32b?version=0.42.2\n"
     ]
    }
   ],
   "source": [
    "@qfunc\n",
    "def rainbow_brute_force(\n",
    "    x1: QNum,\n",
    "    x2: QNum,\n",
    "    ind_reg: QBit,\n",
    ") -> None:\n",
    "    inplace_prepare_state(probabilities, 0, x1)\n",
    "    inplace_prepare_state(probabilities, 0, x2)\n",
    "\n",
    "    max_out = QNum(\"max_out\")\n",
    "    within_apply(\n",
    "        lambda: affine_max(x1, x2, max_out),\n",
    "        lambda: brute_force_payoff(max_out, ind_reg),\n",
    "    )\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def main(\n",
    "    x1: Output[QNum],\n",
    "    x2: Output[QNum],\n",
    "    ind_reg: Output[QBit],\n",
    ") -> None:\n",
    "    allocate(NUM_QUBITS, x1)\n",
    "    allocate(NUM_QUBITS, x2)\n",
    "    allocate(1, ind_reg)\n",
    "    rainbow_brute_force(x1, x2, ind_reg)\n",
    "\n",
    "\n",
    "constraints = Constraints(max_width=23)\n",
    "qmod = create_model(main, constraints=constraints)\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "018f1c60",
   "metadata": {},
   "source": [
    "## IQAE algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "ba92dec8",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:41:17.257828Z",
     "start_time": "2024-04-01T09:41:17.234615Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "from classiq import cfunc, Z\n",
    "from classiq.qmod.builtins.classical_execution_primitives import iqae, save\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def qmci_oracle(ind: QBit):\n",
    "    Z(ind)\n",
    "\n",
    "@cfunc\n",
    "def cmain():\n",
    "    iqae_res = iqae(epsilon=0.01, alpha=0.05)\n",
    "    save({\"iqae_res\": iqae_res})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "5fe090ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "from classiq import CInt, QCallable, grover_operator, power, QArray\n",
    "\n",
    "@qfunc\n",
    "def grover_algorithm(\n",
    "    k: CInt,\n",
    "    oracle_operand: QCallable[QArray[QBit]],\n",
    "    sp_operand: QCallable[QArray[QBit]],\n",
    "    x: QArray[QBit],\n",
    "):\n",
    "    sp_operand(x)\n",
    "    power(k, lambda: grover_operator(oracle_operand, sp_operand, x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "04a7586d",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:41:17.258463Z",
     "start_time": "2024-04-01T09:41:17.242197Z"
    },
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "def get_main():\n",
    "    @qfunc\n",
    "    def main(\n",
    "        k: CInt,\n",
    "        ind_reg: Output[QBit],\n",
    "    ) -> None:\n",
    "        full_reg = QArray(\"full_reg\")\n",
    "        allocate(2 * NUM_QUBITS + 1, full_reg)\n",
    "        grover_algorithm(\n",
    "            k,\n",
    "            lambda x: qmci_oracle(x[x.len - 1]),\n",
    "            lambda x: rainbow_brute_force(\n",
    "                x[0:NUM_QUBITS],\n",
    "                x[NUM_QUBITS : 2 * NUM_QUBITS],\n",
    "                x[x.len - 1],\n",
    "            ),\n",
    "            full_reg,\n",
    "        )\n",
    "        state_reg = QArray(\"state_reg\")\n",
    "        bind(full_reg, [state_reg, ind_reg])\n",
    "\n",
    "    return main"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a6152039",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:41:17.258780Z",
     "start_time": "2024-04-01T09:41:17.247454Z"
    }
   },
   "outputs": [],
   "source": [
    "from classiq import execute, write_qmod\n",
    "from classiq.execution import ExecutionPreferences\n",
    "\n",
    "def synthesize_and_execute(post_process):\n",
    "    constraints = Constraints(max_width=25)\n",
    "    qmod = create_model(\n",
    "        get_main(),\n",
    "        constraints=constraints,\n",
    "        classical_execution_function=cmain,\n",
    "    )\n",
    "    write_qmod(qmod, \"rainbow_options_bruteforce_method\")\n",
    "    print(\"Starting synthesis\")\n",
    "    qprog = synthesize(qmod)\n",
    "    show(qprog)\n",
    "    print(\"Starting execution\")\n",
    "    res = execute(qprog).result()\n",
    "    iqae_res = res[0].value\n",
    "    parsed_res = post_process(res[0].value)\n",
    "\n",
    "    return (qmod, qprog, iqae_res, parsed_res)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d56988f6",
   "metadata": {},
   "source": [
    "## Post Process\n",
    "We need to add to the post-processing function a term:\n",
    "\\begin{equation}\n",
    "\\begin{split}\n",
    "&\\mathbb{E} \\left[\\max\\left(e^{b \\cdot z}, Ke^{-b'}\\right) \\right] e^{b'} - K \\\\\n",
    "= &\\mathbb{E} \\left[\\max\\left(e^{-a\\hat{x}}, Ke^{-b'-ax_{max}}\\right) \\right]e^{b'+ ax_{max}} - K \n",
    "\\end{split}\n",
    "\\end{equation}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "7163ce7b",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:41:17.258984Z",
     "start_time": "2024-04-01T09:41:17.252987Z"
    }
   },
   "outputs": [],
   "source": [
    "import sympy\n",
    "\n",
    "def parse_result_bruteforce(iqae_res):\n",
    "    payoff_expression = f\"sqrt(max({S0[0]} * exp({STEP_X / SCALING_FACTOR * (2 ** (MAX_NUM_QUBITS - MAX_FRAC_PLACES))} * x + ({MU[0]+MIN_X*CHOLESKY[0].sum()})), {K}))\"\n",
    "    payoff_func = sympy.lambdify(sympy.symbols(\"x\"), payoff_expression)\n",
    "    payoff_max = payoff_func(1 - 1 / (2**MAX_NUM_QUBITS)) \n",
    "\n",
    "    option_value = iqae_res.estimation * (payoff_max**2) - K\n",
    "    confidence_interval = np.array(iqae_res.confidence_interval) * (payoff_max**2) - K\n",
    "    return (option_value, confidence_interval)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4258b1db",
   "metadata": {},
   "source": [
    "# Run Method"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "22b75db1",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-01T09:41:49.853139Z",
     "start_time": "2024-04-01T09:41:17.275596Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting synthesis\n",
      "Opening: https://platform.classiq.io/circuit/9b71ebe0-ad90-44e3-9a2b-fdb7a127869b?version=0.42.2\n",
      "Starting execution\n",
      "raw iqae results: 0.5057390928129042 with confidence interval (0.5035438550940906, 0.5079343305317179)\n",
      "option estimated value: 23.68809763877735 with confidence interval [22.76055184 24.61564344]\n"
     ]
    }
   ],
   "source": [
    "qmod_brute_force, qprog_brute_force, iqae_res_brute_force, parsed_res_brute_force = (\n",
    "    synthesize_and_execute(parse_result_bruteforce)\n",
    ")\n",
    "result, conf_interval = parsed_res_brute_force\n",
    "print(\n",
    "    f\"raw iqae results: {iqae_res_brute_force.estimation} with confidence interval {iqae_res_brute_force.confidence_interval}\"\n",
    ")\n",
    "print(f\"option estimated value: {result} with confidence interval {conf_interval}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "21f35b27",
   "metadata": {},
   "outputs": [],
   "source": [
    "assert -5 <= result <= 45"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f1409802",
   "metadata": {},
   "source": [
    "## References\n",
    "\n",
    "<a name='QALROP'>[1]</a>: [Francesca Cibrario et al., Quantum Amplitude Loading for Rainbow Options Pricing. Preprint](https://arxiv.org/abs/2402.05574v2)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
